package stark.app.webserver;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.util.concurrent.TimeUnit;

import stark.common.basic.device.NetUtil;

/**
 * <pre>
 *     author : cfans
 *     time   : 2020/11/21
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class WebServerService extends Service {
    private Server mServer;
    public static final int SERVER_PORT = 8065; //8066;

    @Override
    public void onCreate() {
        mServer = AndServer.webServer(this)
                .port(SERVER_PORT)
                .timeout(10, TimeUnit.SECONDS)
                .listener(new Server.ServerListener() {
                    @Override
                    public void onStarted() {
                        String address = NetUtil.getIpAddressString();
                        WebServerManager.shared().onServerStart(WebServerService.this, address);
                    }

                    @Override
                    public void onStopped() {
                        WebServerManager.shared().onServerStop(WebServerService.this);
                    }

                    @Override
                    public void onException(Exception e) {
                        WebServerManager.shared().onServerError(WebServerService.this, e.getMessage());
                    }
                })
                .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startServer();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        stopServer();
        super.onDestroy();
    }

    /**
     * Start server.
     */
    private void startServer() {
        mServer.startup();
    }

    /**
     * Stop server.
     */
    private void stopServer() {
        mServer.shutdown();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
